package api

import (
	"errors"
	"net/http"
	"strconv"

	"github.com/emicklei/go-restful"
	restfulspec "github.com/emicklei/go-restful-openapi"

	"github.com/xdhuxc/asset-management-system/src/model"
	"github.com/xdhuxc/asset-management-system/src/pkg"
)

type userController struct {
	*BaseController
}

func newUserController(bc *BaseController) *userController {
	tags := []string{"ams-user"}
	uc := &userController{bc}

	uc.ws.Route(uc.ws.POST("/user/auth").
		To(uc.Auth).
		Doc("health check").
		Metadata(restfulspec.KeyOpenAPITags, tags).
		Reads(&model.User{}).
		Returns(http.StatusOK, "OK", model.Result{}).
		Returns(http.StatusBadRequest, "ERROR", model.Result{}))

	return uc
}

func (uc *userController) Auth(req *restful.Request, resp *restful.Response) {
	var user model.User

	if err := req.ReadEntity(&user); err != nil {
		pkg.WriteResponse(resp, pkg.AuthorityError, err)
	}

	result, err := uc.bs.UserService.Auth(user.Name, user.Password)
	if err != nil {
		pkg.WriteResponse(resp, pkg.AuthorityError, errors.New("认证失败"))
		return
	}

	result.Token = strconv.Itoa(result.ID)

	_ = resp.WriteEntity(model.NewResult(0, nil, result))
}
